import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import vueJsx from "@vitejs/plugin-vue-jsx";
import VueSetupExtend from "vite-plugin-vue-setup-extend";
import topLevelAwait from "vite-plugin-top-level-await";
import monacoEditorPlugin from "vite-plugin-monaco-editor";
import scanViewsPlugin from "./plugins/scan-views";
import path from "path";


// 手动处理字体文件的Rollup插件
const fontHandlingPlugin = {
  name: 'font-handler',
  // Rollup的load钩子用于加载特定类型的文件
  load(id: string) {
    // 匹配字体文件
    if (/\.ttf$/.test(id) || /\.woff2?$/.test(id) || /\.eot$/.test(id) || /\.otf$/.test(id)) {
      // 生成一个导出文件路径的模块
      const filePath = path.relative(process.cwd(), id)
      return `export default new URL('${filePath}', import.meta.url).href`
    }
  }
}

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    scanViewsPlugin(),
    topLevelAwait(),
    VueSetupExtend(),
    vueJsx(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
      eslintrc: {
        enabled: false, // Default `false`
        filepath: "./.eslintrc-auto-import.json", // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
      },
    }),
    Components({
      // 指定组件所在文件夹的位置，默认是src/components
      dirs: ["components"],
      // ui库解析器
      resolvers: [ElementPlusResolver({ importStyle: "sass" })],
      extensions: ["vue"], //文件扩展
      // 配置type文件生成位置
      dts: true,
    }),
    monacoEditorPlugin({
      languageWorkers: ['json', 'typescript', 'editorWorkerService'],
      customDistPath: () => resolve(__dirname, '../dist/monaco-editor/'),
      publicPath: 'monaco-editor',
    }),
    fontHandlingPlugin,
  ],
  root: resolve(__dirname, "./src"),
  publicDir: resolve(__dirname, "./public"),
  // 存储缓存文件的目录地址
  cacheDir: "",
  //
  resolve: {
    extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    // 设置文件目录别名
    // 根目录地址变更，也需要调整
    alias: {
      "@": resolve(__dirname, "./src"),
      "@components": resolve(__dirname, "./src/components"),
      vue: "vue/dist/vue.esm-bundler.js", // 定义vue的别名，如果使用其他的插件，可能会用到别名
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "@/styles/element/index.scss" as *;`,
        api: "modern-compiler", // 修改api调用方式
      },
    },
  },
  base: "/",
  assetsInclude: ['**/*.ttf', '**/*.woff', '**/*.woff2', '**/*.eot', '**/*.otf'],
  // 构建配置项
  build: {
    // ...
    // 指定输出目录
    outDir: resolve(__dirname, "./dist"),
    // 指定静态资源存放目录
    assetsDir: "",
    // 启用、禁用css代码拆分
    cssCodeSplit: true,
    // 构建是否生成source map文件
    sourcemap: "inline",
    chunkSizeWarningLimit: 3000,
    // rollup 配置打包项
    rollupOptions: {
      input: {
        main: resolve(__dirname, "src/index.html"),
        login: resolve(__dirname, "src/login.html"),
      },
      output: {
        manualChunks: {
          // 其他第三方库单独拆分
          'vendor': ['vue', 'vue-router']
        }, // 禁用代码拆分
        /*manualChunks(id) {
          if (id.includes("node_modules")) {
            return id
              .toString()
              .split("node_modules/")[1]
              .split("/")[0]
              .toString();
          }
        },*/
        // 配置字体文件的输出路径
        assetFileNames: (assetInfo) => {
          if (/\.(ttf|woff|woff2|eot|otf)$/.test(assetInfo.name || '')) {
            return 'fonts/[name]-[hash][extname]'
          }
          return 'assets/[name]-[hash][extname]'
        }
      },
    },
    // 构建目录自动清除
    emptyOutDir: false,
  },
  server: {
    proxy: {
      "/srv": {
        target: "http://localhost:18888", // 后端接口地址
        changeOrigin: true, // 开启跨域
        rewrite: (path) => path.replace(/^\/srv/, ""), // 重写路径
      },
    },
  },
});
